Skip to content

fix(artists): cache popular-artists fallback in Redis (suggestions empty bug) - #707

Merged
LucasSantana-Dev merged 2 commits into
mainfrom
fix/artist-suggestions-cache
Apr 18, 2026
Merged

LucasSantana-Dev merged 2 commits into
mainfrom
fix/artist-suggestions-cache

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 18, 2026 •

Copy link
Copy Markdown
Owner

Bug

/api/artists/suggestions returns {"artists":[]} on production. Page shows 'No suggestions available'.

Root cause

Spotify search API returns 429 (rate-limited). Each page load fans out 8+ search calls (Drake, The Weeknd, Dua Lipa, etc.). Without caching, this saturates Spotify quota fast and starts returning empty.

Fix

Cache the popular-artists fallback bundle in Redis (key artist:suggestions:fallback:v1, TTL 1h). First request populates, subsequent reads bypass Spotify. Also bumped the query list from 8 → 12 artists for variety.

Summary by CodeRabbit

  • Improvements
    • Enhanced artist suggestions endpoint with improved fallback logic and caching, providing faster load times and more reliable results when fetching popular artists.

Spotify search API rate-limits us (429) when every page load fans out
to 8+ search queries. Symptom: /api/artists/suggestions returns
{artists:[]} → page shows 'No suggestions available' even though the
endpoint reports 200.

Cache the fallback bundle in Redis with a 1h TTL keyed by version.
First request populates, subsequent reads bypass Spotify entirely.
Also bumped the query list from 8 → 12 popular artists.
@LucasSantana-Dev
LucasSantana-Dev enabled auto-merge (squash) April 18, 2026 12:16
@vercel

vercel Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Apr 18, 2026 0:26am

Request Review

@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 51 minutes and 37 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 51 minutes and 37 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5eac249d-e5c3-414c-a465-1337280e16f5

📥 Commits

Reviewing files that changed from the base of the PR and between 48a087e and 84e297c.

📒 Files selected for processing (1)
  • packages/backend/tests/unit/routes/artists.test.ts
📝 Walkthrough

Walkthrough

The /api/artists/suggestions route now implements Redis-backed caching for the popular artists fallback. When fallback is triggered, the route checks Redis for a cached artist bundle, and if absent, fetches artists via multiple Spotify search queries with deduplication, then caches the result for one hour. The inline fixed query list was removed.

Changes

Cohort / File(s) Summary
Redis Caching for Artist Suggestions
packages/backend/src/routes/artists.ts
Replaces inline fixed artist list with Redis-backed caching. Added Redis lookup on fallback, dynamic artist fetching via searchSpotifyArtists with ID-based deduplication, and cache write with 1-hour TTL. Control flow now checks cache before live Spotify search.

Sequence Diagram(s)

sequenceDiagram
    actor Client
    participant API as API Route
    participant Redis
    participant Spotify as Spotify API

    Client->>API: GET /api/artists/suggestions
    
    alt Popular Artists Fallback Needed
        API->>Redis: get(POPULAR_ARTISTS_KEY)
        alt Cache Hit
            Redis-->>API: cached artist bundle
        else Cache Miss
            API->>Spotify: Multiple searchSpotifyArtists queries
            Spotify-->>API: artist results
            API->>API: deduplicate by ID
            API->>Redis: setex(POPULAR_ARTISTS_KEY, 3600, artists)
            Redis-->>API: OK
        end
        API->>API: merge artists into suggestions (up to 24 total)
    end
    
    API-->>Client: suggestions response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested labels

backend, size/m

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and accurately describes the main change: caching popular artists in Redis to fix the empty suggestions bug caused by Spotify rate limiting.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/artist-suggestions-cache

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/backend/src/routes/artists.ts`:
- Around line 126-132: The Redis-cached payload read via
redisClient.get(FALLBACK_SUGGESTIONS_CACHE_KEY) is used without validating its
shape, so a non-array or malformed JSON will cause fallback.length/iteration
errors; update the try blocks around redisClient.get(...) (and the similar code
near lines handling the same key) to JSON.parse the cached value then verify
it's an array of SpotifyArtist-like objects (e.g., Array.isArray(parsed) and
optional checks for expected fields) before assigning to the fallback variable;
if validation fails, ignore the cache (leave fallback as the live-fetch
sentinel) and proceed to fetch from Spotify to prevent 500s.
- Around line 137-181: The fallback-population code currently lets concurrent
requests run the 12-query loop and can cache partial results; fix by using a
Redis single-flight lock via redisClient.setNxPx() on
FALLBACK_SUGGESTIONS_CACHE_KEY (or a derived lock key) before running the
suggestQueries loop so only one process populates at a time, have other callers
detect the lock (read the cache in a short retry/backoff loop and return cached
value if populated), and only call redisClient.setex to cache results if
fallback.length meets a minimum threshold (e.g., >= 24 or a configurable
populationThreshold); always release the lock (delete the lock key) in a finally
block and on failures avoid caching partial results or use a much shorter TTL
variable instead of FALLBACK_SUGGESTIONS_TTL_SECONDS.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3bbfb3a5-c436-41ba-93b8-d4da68cec8b9

📥 Commits

Reviewing files that changed from the base of the PR and between 19f94ef and 48a087e.

📒 Files selected for processing (1)
  • packages/backend/src/routes/artists.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Quality Gates
  • GitHub Check: SonarCloud Scan
🔇 Additional comments (1)
packages/backend/src/routes/artists.ts (1)

16-19: LGTM: cache dependency and TTL are scoped cleanly.

The fixed key and 1-hour TTL match the fallback-bundle caching objective.

Comment thread packages/backend/src/routes/artists.ts
Comment thread packages/backend/src/routes/artists.ts
@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 5589edb into main Apr 18, 2026
12 checks passed
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…pty bug) (#707)

* fix(artists): cache popular-artists fallback in Redis (1h)

Spotify search API rate-limits us (429) when every page load fans out
to 8+ search queries. Symptom: /api/artists/suggestions returns
{artists:[]} → page shows 'No suggestions available' even though the
endpoint reports 200.

Cache the fallback bundle in Redis with a 1h TTL keyed by version.
First request populates, subsequent reads bypass Spotify entirely.
Also bumped the query list from 8 → 12 popular artists.

* test(backend): mock redisClient for artists suggestions cache
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/artist-suggestions-cache branch May 23, 2026 02:21

This branch was successfully deployed

1 active deployment
Preview — 84e297c1 Deployed Apr 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant